# Create your views here.
#from l2ldjango.apps.blog.views import *
from l2ldjango.apps.firm.models import *
from l2ldjango.apps.firm.forms import *
from django.template import RequestContext 
from django.shortcuts import render_to_response, get_object_or_404
from l2ldjango.settings import DATABASES
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from l2ldjango.apps.usermanagement.views import *
from django.core.mail import EmailMessage
from l2ldjango.apps.usermanagement.models import *

from django.core.paginator import Paginator, InvalidPage, EmptyPage

from django.db.models import Q

@login_required
def getFriends(userid):
    usr=userid.user.id
    #usr=User.objects.get(pk=userid)
    f=Friends.objects.filter(initiator=usr,status='APPROVED')
    return f

def runquery(qry):
    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost",DATABASES['default']['USER'],DATABASES['default']['PASSWORD'],DATABASES['default']['NAME'] )
    
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    
    # execute SQL query using execute() method.
    cursor.execute(qry)
    
    # Fetch a single row using fetchone() method.
    #data = cursor.fetchone()
    
    #print "Database version : %s " % data
    
    # disconnect from server
    db.close()

@login_required
def view_referrals(request):
    
    form = SearchForm(initial={'the_state':'NY'})
    
    results = userprofile.objects.filter(Q(accepting_referrals=True) | 
                                         Q(available_per_diem=True))
    
    if request.GET:
        
        form = SearchForm(request.GET)
        
        if request.GET.has_key('name') and len(request.GET['name']) > 0:
            results = results.filter(full_name__icontains=request.GET['name'])
        if request.GET.has_key('the_county') and len(request.GET['the_county']) > 0:
            try:
                results = results.filter(office_county=request.GET['the_county'])
            except Exception,err:
                raise Http404
            
    paginator = Paginator(results, 25) # Show 25 contacts per page

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        profiles = paginator.page(page)
    except (EmptyPage, InvalidPage):
        profiles = paginator.page(paginator.num_pages)

    
    return render_to_response('firm/referrals.html',
                          {'form':form,
                           'profiles':profiles,
                           'title':'Existing Firms',},
                          context_instance=RequestContext(request))

@login_required
def view_all(request):
    
    form = SearchForm(initial={'the_state':'NY'})
    
    results = userprofile.objects.all()
    
    if request.GET:
        
        form = SearchForm(request.GET)
        
        if request.GET.has_key('name') and len(request.GET['name']) > 0:
            results = results.filter(full_name__icontains=request.GET['name'])
        if request.GET.has_key('the_county') and len(request.GET['the_county']) > 0:
            try:
                results = results.filter(office_county=request.GET['the_county'])
            except Exception,err:
                raise Http404
            
    paginator = Paginator(results, 25) # Show 25 contacts per page

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        profiles = paginator.page(page)
    except (EmptyPage, InvalidPage):
        profiles = paginator.page(paginator.num_pages)

    
    return render_to_response('firm/firms.html',
                          {'form':form,
                           'profiles':profiles,
                           'title':'Existing Firms',},
                          context_instance=RequestContext(request))


@login_required
def joinFirm(request,firmid):
    #firm_dtl=Firm.objects.get(pk=firmid)
    try:
        firm_dtl=Firm.objects.get(pk=firmid,verification_code=request.POST['verification_code'])
        fg=FirmGroup()
        fg.member=request.user
        fg.firm=firm_dtl
        fg.save()
        title="Successfully joined to the Firm"
        message="Verification Code matches,Congratualaions!!You now belong to this Firm."
    except ObjectDoesNotExist:    
        title="Verification Code mismatch"
        message="Verification Code didn't match,Please Check you code."
            
    firm_dtl=Firm.objects.get(pk=firmid)
    try:
        firm_grp=FirmGroup.objects.get(firm=firm_dtl,member=request.user)
        show_join=False
    except ObjectDoesNotExist:   
        show_join=True
    firm_members=FirmGroup.objects.filter(firm=firm_dtl)    
    variables = RequestContext(request,{'members':firm_members,'show_join':show_join,'firm_dtl':firm_dtl,'title':title,'message':message})    
    #return HttpResponse(blogs);
    return render_to_response('firm/view_firm.html',variables) 

@login_required
def firmEdit(request,firmid):
    firm=Firm.objects.get(id=firmid)
    if firm.created_by.id==request.user.id:
        if request.method == 'POST':
            form=FirmForm(request.POST,instance=firm)
            if form.is_valid():
                form.save()
                title="Updated Successfully."
                message="Fim Updated."
                variables = RequestContext(request,{'title':title,'message':message,'firmid':firmid,'form':form})    
                return render_to_response('firm/edit_firm.html',variables) 
            else:
                err=form.errors                
                title="Error Saving"                
                #message="You are not the author of blog which you are tying to edit."
                variables = RequestContext(request,{'title':title,'firmid':firmid,'form':form,'message':err})    
                return render_to_response('firm/edit_firm.html',variables)
        else:
            form=FirmForm(instance=firm)
            title="Edit"
            #message="You are not the author of blog which you are tying to edit."
            variables = RequestContext(request,{'title':title,'firmid':firmid,'form':form})    
            return render_to_response('firm/edit_firm.html',variables)
        #do somentihg
    else:
        title="Permission denied."
        message="You cannot edit firm created by others."
        variables = RequestContext(request,{'title':title,'message':message})    
        return render_to_response('pages/success_page.html',variables) 


@login_required
def SendJoinRequest(request,friendid,firmid):
    usr=User.objects.get(pk=friendid)
    email=usr.email
    #email="mahesh@wework4web.com"
    email_from=request.user.email
    firm=Firm.objects.get(pk=firmid)
    verification_code=firm.verification_code
    #send notification to the requested user to join the firm
    addlink='%s%s%s'%('<a href="http://destructible.me/l2l/firm/detail/',firm.id,'">click here</a>')
    email_message='%s%s%s%s%s%s%s'%(email_from,'has sent you a Group request to join a Firm <strong>',firm.firm_name,'</strong> from L2L.<br>verification code:',verification_code,'<br/>Please click link below and enter your verification code to Join the Firm.<br/>',addlink)
    msg=EmailMessage('L2L,Join Firm-Firm activation Key',email_message,email_from,[email])
    msg.content_subtype="html"
    msg.send()
    title="Request sent"
    message="Message with firm's code has been sent to Your Friend"
    variables = RequestContext(request,{'title':title,'message':message})    
    return render_to_response('pages/success_page.html',variables) 

@login_required
def firmDtl(request,firmid):
    #get friend list of user who is viewing the firm
    frnds=getFriends(request)
    firm_dtl=Firm.objects.get(pk=firmid)
    try:
        firm_grp=FirmGroup.objects.get(firm=firm_dtl,member=request.user)
        show_join=False
    except ObjectDoesNotExist:   
        show_join=True
    firm_members=FirmGroup.objects.filter(firm=firm_dtl)
    firm_members_list=[]
    for f in firm_members:
        firm_members_list.append(f.member.id)
        
        
    variables = RequestContext(request,{'member_list':firm_members_list,'friends':frnds,'members':firm_members,'show_join':show_join,'firm_dtl':firm_dtl,'title':'Firm Details'})    
    #return HttpResponse(blogs);
    return render_to_response('firm/view_firm.html',variables) 

def getMemberFirmsOf(userid):
      firms=FirmGroup.objects.filter(member=userid)
      return firms

import random
def getRamdomCode(code_range):
    return random.randrange(code_range)
 
@login_required
def addFirm(request):
    try:
        f=Firm.objects.get(created_by=request.user)
        message="%s%s"%('You Have already Created a Firm ',f.firm_name)
        variables = RequestContext(request,{'title':'Cannot Add More than 1 Firm','message':message})    
        return render_to_response('firm/add_new_firm.html',variables) 
    except ObjectDoesNotExist:             
        if request.method == 'POST':
            form = FirmForm(request.POST)
            if form.is_valid():
                qs=form.save()
                qs_obj=Firm.objects.get(pk=qs.id)
                qs_obj.created_by=request.user
                qs_obj.verification_code=getRamdomCode(999999999)
                qs_obj.save()
                #send message to the firm creator with verification code
                #email='themaheshe1@gmail.com'
                email=request.user.email
                addlink='%s%s%s%s%s'%('Firm Created Successfully ,',qs_obj.firm_name,'. Your Verification Code for Created Firm is ',qs_obj.verification_code,'.You can send this code to your friend to add to Your Firm Directly via L2L Account.')
                email_message=addlink
                send_mail('L2L Firm Verification Key',email_message, 'no-reply@lawyertolawyerny.com',[email], fail_silently=False)
                variables = RequestContext(request,{'title':'success message','message':'Firm Successfully Created.'})    
                return render_to_response('pages/success_page.html',variables) 
                
            else:
                errs=form.errors
                variables = RequestContext(request,{'form': form,'message':errs})
                return render_to_response('firm/add_new_firm.html',variables)    
                
        else:
            form=FirmForm() 
            variables = RequestContext(request,{'form':form,'title':'Add Firm','message':'Create Firm,Invite Attorneys to Your Firm.'})    
            return render_to_response('firm/add_new_firm.html',variables) 
    
